package com.wchat.server.handler;

import com.wchat.server.ClientManager;
import com.wchat.utils.BeanUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author : willian fu
 * @date : 2020/5/26
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class HeartbeatHandler extends IdleStateHandler {

    @Autowired
    private ClientManager clientManager;

    public static Integer HEARTBEAT_TIME = 20;

    public HeartbeatHandler() {
        super(HEARTBEAT_TIME, 0, 0, TimeUnit.SECONDS);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        log.warn("{}S内未获取到设备消息，心跳检测超时，断开连接-", HEARTBEAT_TIME);
        clientManager.offline(ctx.channel());
        ctx.close();
    }
}
